import dayjs from "dayjs";
import CryptoJS from "crypto-js";

/**
 * api加密
 * @param baseUri api地址 eg. /api/index/index
 * @param args 参数obj
 */
export default (baseUri, args) => {
	try {
		const timestamp = dayjs().valueOf().toString().slice(0, 10);
		const random = Math.floor(Math.random() * 25).toString();
		const md5 = CryptoJS.MD5(`${baseUri}${random}${timestamp}`)
			.toString()
			.toUpperCase();
		const key = md5.slice(parseInt(random), parseInt(random) + 8) + "qmg";
		const hex = key
			.split("")
			.map((_, i) => {
				const charCode = key.charCodeAt(i);
				const hexValue = charCode.toString(16);
				return hexValue.padStart(2, "0");
			})
			.join("")
			.slice(0, 16);
		const nonce = CryptoJS.MD5(
			(args === "" ? "" : JSON.stringify(args)) +
			timestamp +
			Math.random() * 10000
		).toString();
		const aes = CryptoJS.AES.encrypt(
			CryptoJS.enc.Utf8.parse(nonce + md5),
			CryptoJS.enc.Utf8.parse(hex), {
				mode: CryptoJS.mode.ECB,
				padding: CryptoJS.pad.Pkcs7,
			}
		);
		const s = CryptoJS.MD5(aes.toString()).toString().split("");
		s[6] = random.length === 1 ? "0" : random[0];
		s[17] = random.length === 1 ? random : random[1];
		const sign = s.join("");
		return {
			sign,
			timestamp,
			nonce
		};
	} catch (error) {
		console.log(error);
	}
};